﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Models;
using Utils;
using System.Reflection;
using System.Linq.Expressions;

namespace Services
{
    public class WorkPieceDataCaptureRespository
    {
        private readonly IServiceProvider _serviceProvider;
        public WorkPieceDataCaptureRespository(IServiceProvider serviceProvider)
        {
            this._serviceProvider = serviceProvider;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        public FuncResult<List<tb_WorkPieceDataCapture_Realtime>> loadData()
        {
            var result = new FuncResult<List<tb_WorkPieceDataCapture_Realtime>>();
            try
            {
                var _context = this._serviceProvider.GetService<AppDbContext>();
                if (_context != null)
                {
                    result.obj_Return = _context.tb_workpiecedatacapture_realtime.Where(eee => eee.dDate == null).ToList();
                    result.bSuccess = true;
                }
                else
                {
                    result.bSuccess = false;
                    result.strMsg = "无法获取到数据库服务";
                }
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }

        /// <summary>
        /// 根据总成标识码查询数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public FuncResult<tb_WorkPieceDataCapture_Realtime> getBySerialNoFromRealTime(string serialNo)
        {
            var result = new FuncResult<tb_WorkPieceDataCapture_Realtime>();
            try
            {
                var _context = this._serviceProvider.GetService<AppDbContext>();
                if (_context != null)
                {
                    var obj = _context.tb_workpiecedatacapture_realtime.FirstOrDefault(w => w.ZC_SerialNo == serialNo);
                    result.obj_Return = obj;
                    result.bSuccess = true;
                }
                else
                {
                    result.bSuccess = false;
                    result.strMsg = "无法获取到数据库服务";
                }
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }

        /// <summary>
        /// 根据总成激光码查询数据
        /// </summary>
        /// <param name="laserNo"></param>
        /// <returns></returns>
        public FuncResult<tb_WorkPieceDataCapture_Realtime> getByLaserNoFromRealTime(string laserNo)
        {
            var result = new FuncResult<tb_WorkPieceDataCapture_Realtime>();
            try
            {
                var _context = this._serviceProvider.GetService<AppDbContext>();
                if (_context != null)
                {
                    var obj = _context.tb_workpiecedatacapture_realtime.FirstOrDefault(w => w.ZC_LaserNo == laserNo);
                    result.obj_Return = obj;
                    result.bSuccess = true;
                }
                else
                {
                    result.bSuccess = false;
                    result.strMsg = "无法获取到数据库服务";
                }
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }
        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public FuncResult<int> saveData(tb_WorkPieceDataCapture_Realtime model)
        {
            var result = new FuncResult<int>();
            try
            {
                var _context = this._serviceProvider.GetService<AppDbContext>();
                if (_context != null)
                {
                    _context.tb_workpiecedatacapture_realtime.Add(model);
                    result.bSuccess = true;
                    result.obj_Return = _context.SaveChanges();
                }
                else
                {
                    result.bSuccess = false;
                    result.strMsg = "无法获取到数据库服务";
                }
            }
            catch (Exception ex)
            {
                result.setException(ex);
                result.obj_Return = 0;
            }
            return result;
        }
        /// <summary>
        /// 获取今日产量与24小时产量简单统计数据
        /// </summary>
        /// <returns></returns>
        public FuncResult<ProduceSummary> getProduceSummary()
        {
            var result = new FuncResult<ProduceSummary>();
            var summary = new ProduceSummary();
            int nowyear, nowmonth, nowday;
            try
            {
                var _context = this._serviceProvider.GetService<AppDbContext>();
                if (_context != null)
                {
                    nowyear = DateTime.Now.Year;
                    nowmonth = DateTime.Now.Month;
                    nowday = DateTime.Now.Day;
                    var data = new
                    {
                        CL_OK_24Hour = _context.tb_workpiecedatacapture_realtime
                            .Where(w => w.dDate >= DateTime.Now.AddDays(-1) && w.dDate <= DateTime.Now && w.ZC_Result == "OK")
                            .Count(),
                        CL_NG_24Hour = _context.tb_workpiecedatacapture_realtime
                            .Where(w => w.dDate >= DateTime.Now.AddDays(-1) && w.dDate <= DateTime.Now && w.ZC_Result == "NG")
                            .Count(),
                        CL_OK_Today = _context.tb_workpiecedatacapture_realtime
                            .Where(w => w.dDate >= new DateTime(nowyear, nowmonth, nowday) && w.dDate <= new DateTime(nowyear, nowmonth, nowday).AddDays(1).AddTicks(-1) && w.ZC_Result == "OK")
                            .Count(),
                        CL_NG_Today = _context.tb_workpiecedatacapture_realtime
                            .Where(w => w.dDate >= new DateTime(nowyear, nowmonth, nowday) && w.dDate <= new DateTime(nowyear, nowmonth, nowday).AddDays(1).AddTicks(-1) && w.ZC_Result == "NG")
                            .Count()
                    };
                    summary.OK24Hour = data.CL_OK_24Hour;   //24小时的OK产量
                    summary.NG24Hour = data.CL_NG_24Hour;   //24小时的NG产量
                    summary.production24Hour = data.CL_OK_24Hour + data.CL_NG_24Hour;   //24小时的总产量
                    summary.OKRate24Hour = MathMethods.CalculatePercentage(summary.OK24Hour, summary.production24Hour);    //24小时良品率
                    summary.OKToday = data.CL_OK_Today; //今日OK产量
                    summary.NGToday = data.CL_NG_Today; //今日NG产量
                    summary.productionToday = data.CL_OK_Today + data.CL_NG_Today;  //今日总产量
                    summary.OKRateToday = MathMethods.CalculatePercentage(summary.OKToday, summary.productionToday);   //今日良品率
                    result.bSuccess = true;
                    result.obj_Return = summary;
                }
                else
                {
                    result.bSuccess = false;
                    result.strMsg = "无法获取到数据库服务";
                }
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }

        /// <summary>
        /// 到实时数据表里根据查询条件查询数据
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="dbSet"></param>
        /// <returns></returns>
        public FuncResult<List<tb_WorkPieceDataCapture_Realtime>> SearchDataFromRealTimeTable(model_SearchCondition conditions, DbSet<tb_WorkPieceDataCapture_Realtime> dbSet)
        {
            var result = new FuncResult<List<tb_WorkPieceDataCapture_Realtime>>();
            try
            {
                var query = from wpc in dbSet
                            where (conditions.ZC_SerialNo == null ? true : wpc.ZC_SerialNo.Contains(conditions.ZC_SerialNo)) &&
                                  (conditions.ZC_Model == null ? true : wpc.ZC_Model.Contains(conditions.ZC_Model)) &&
                                  (conditions.dDate_Begin == null ? true : wpc.dDate >= new DateTime(conditions.dDate_Begin.Value.Year, conditions.dDate_Begin.Value.Month, conditions.dDate_Begin.Value.Day, 0, 0, 0)) &&
                                  (conditions.dDate_End == null ? true : wpc.dDate <= new DateTime(conditions.dDate_End.Value.Year, conditions.dDate_End.Value.Month, conditions.dDate_End.Value.Day, 23, 59, 59)) &&
                                  (conditions.ZC_LaserNo == null ? true : wpc.ZC_LaserNo.Contains(conditions.ZC_LaserNo)) &&
                                  (conditions.ZC_Result == null ? true : wpc.ZC_Result.Contains(conditions.ZC_Result.Replace("全部", ""))) &&
                                  (conditions.FLJ_ZT_Model == null ? true : wpc.FLJ_ZT_Model.Contains(conditions.FLJ_ZT_Model)) &&
                                  (conditions.FLJ_ZT_Material == null ? true : wpc.FLJ_ZT_Material.Contains(conditions.FLJ_ZT_Material)) &&
                                  (conditions.FLJ_YCQ_Model == null ? true : wpc.FLJ_YCQ_Model.Contains(conditions.FLJ_YCQ_Model)) &&
                                  (conditions.FLJ_YCQ_Material == null ? true : wpc.FLJ_YCQ_Material.Contains(conditions.FLJ_YCQ_Material)) &&
                                  (conditions.FLJ_YCQ_Result == null ? true : wpc.FLJ_YCQ_Result.Contains(conditions.FLJ_YCQ_Result.Replace("全部", ""))) &&
                                  (conditions.FLJ_GLH_Model == null ? true : wpc.FLJ_GLH_Model.Contains(conditions.FLJ_GLH_Model)) &&
                                  (conditions.FLJ_GLH_Material == null ? true : wpc.FLJ_GLH_Material.Contains(conditions.FLJ_GLH_Material)) &&
                                  (conditions.FLJ_GLH_Result == null ? true : wpc.FLJ_GLH_Result.Contains(conditions.FLJ_GLH_Result.Replace("全部", ""))) &&
                                  (conditions.FLJ_ECQ_Model == null ? true : wpc.FLJ_ECQ_Model.Contains(conditions.FLJ_ECQ_Model)) &&
                                  (conditions.FLJ_ECQ_Material == null ? true : wpc.FLJ_ECQ_Material.Contains(conditions.FLJ_ECQ_Material)) &&
                                  (conditions.FLJ_ECQ_Result == null ? true : wpc.FLJ_ECQ_Result.Contains(conditions.FLJ_ECQ_Result.Replace("全部", ""))) &&
                                  (conditions.FLJ_KZH_Model == null ? true : wpc.FLJ_KZH_Model.Contains(conditions.FLJ_KZH_Model)) &&
                                  (conditions.FLJ_KZH_Material == null ? true : wpc.FLJ_KZH_Material.Contains(conditions.FLJ_KZH_Material)) &&
                                  (conditions.FLJ_KZH_Result == null ? true : wpc.FLJ_KZH_Result.Contains(conditions.FLJ_KZH_Result.Replace("全部", ""))) &&
                                  (conditions.FLJ_KZH_Begin == null ? true : wpc.FLJ_KZH_Value >= conditions.FLJ_KZH_Begin) &&
                                  (conditions.FLJ_KZH_End == null ? true : wpc.FLJ_KZH_Value <= conditions.FLJ_KZH_End) &&
                                  (conditions.FLJ_SK_Model == null ? true : wpc.FLJ_SK_Model.Contains(conditions.FLJ_SK_Model)) &&
                                  (conditions.FLJ_SK_Material == null ? true : wpc.FLJ_SK_Material.Contains(conditions.FLJ_SK_Material)) &&
                                  (conditions.FLJ_SK_Result == null ? true : wpc.FLJ_SK_Result.Contains(conditions.FLJ_SK_Result.Replace("全部", ""))) &&
                                  (conditions.JCY_QM_Result == null ? true : wpc.JCY_QM_Result.Contains(conditions.JCY_QM_Result.Replace("全部", ""))) &&
                                  (conditions.JCY_QM_Program == null ? true : wpc.JCY_QM_Program == conditions.JCY_QM_Program) &&
                                  (conditions.JCY_QM_Pressure_Begin == null ? true : wpc.JCY_QM_Pressure >= conditions.JCY_QM_Pressure_Begin) &&
                                  (conditions.JCY_QM_Pressure_End == null ? true : wpc.JCY_QM_Pressure <= conditions.JCY_QM_Pressure_End) &&
                                  (conditions.JCY_QM_Leak_Begin == null ? true : wpc.JCY_QM_Leak >= conditions.JCY_QM_Leak_Begin) &&
                                  (conditions.JCY_QM_Leak_End == null ? true : wpc.JCY_QM_Leak <= conditions.JCY_QM_Leak_End) &&
                                  (conditions.JCY_KTQM_Result == null ? true : wpc.JCY_KTQM_Result.Contains(conditions.JCY_KTQM_Result.Replace("全部", ""))) &&
                                  (conditions.JCY_KTQM_Program == null ? true : wpc.JCY_KTQM_Program == conditions.JCY_KTQM_Program) &&
                                  (conditions.JCY_KTQM_Pressure_Begin == null ? true : wpc.JCY_KTQM_Pressure >= conditions.JCY_KTQM_Pressure_Begin) &&
                                  (conditions.JCY_KTQM_Pressure_End == null ? true : wpc.JCY_KTQM_Pressure <= conditions.JCY_KTQM_Pressure_End) &&
                                  (conditions.JCY_KTQM_Leak_Begin == null ? true : wpc.JCY_KTQM_Leak >= conditions.JCY_KTQM_Leak_Begin) &&
                                  (conditions.JCY_KTQM_Leak_End == null ? true : wpc.JCY_KTQM_Leak <= conditions.JCY_KTQM_Leak_End) &&
                                  (conditions.FLJ_WM_Result == null ? true : wpc.FLJ_WM_Result.Contains(conditions.FLJ_WM_Result.Replace("全部", ""))) &&
                                  (conditions.FLJ_WM_Model == null ? true : wpc.FLJ_WM_Model.Contains(conditions.FLJ_WM_Model)) &&
                                  (conditions.FLJ_WM_Material == null ? true : wpc.FLJ_WM_Material.Contains(conditions.FLJ_WM_Material)) &&
                                  (conditions.ZC_DM_Result == null ? true : wpc.ZC_DM_Result.Contains(conditions.ZC_DM_Result.Replace("全部", ""))) &&
                                  (conditions.ZC_DM_ScanText == null ? true : wpc.ZC_DM_ScanText.Contains(conditions.ZC_DM_ScanText))
                            orderby wpc.ZC_Time descending
                            select wpc;
                var list = query.ToList();
                result.obj_Return = list;
                result.bSuccess = true;
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }
        
        /// <summary>
        /// 数据归档
        /// </summary>
        /// <returns></returns>
        public Task<FuncResult<string>> DataArchivingAsync()
        {
            FuncResult<string> result = new FuncResult<string>();
            try
            {
                var _context = this._serviceProvider.GetService<AppDbContext>();
                var command = _context.Database.ExecuteSqlRaw("call saveData_main();");
                if (command >= 0) result.bSuccess = true;
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return Task.FromResult(result);
        }

        /// <summary>
        /// 新增点检数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public FuncResult<tb_PointCheckRecord> saveData(tb_PointCheckRecord model)
        {
            var result = new FuncResult<tb_PointCheckRecord>();
            try
            {
                var _context = this._serviceProvider.GetService<AppDbContext>();
                if (_context != null)
                {
                    _context.tb_PointCheckRecord.Add(model);
                    result.bSuccess = true;
                    _context.SaveChanges();
                    result.obj_Return = model;
                }
                else
                {
                    result.bSuccess = false;
                    result.strMsg = "无法获取到数据库服务";
                }
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }

        /// <summary>
        /// 根据条件查询点检表数据
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="dbSet"></param>
        /// <returns></returns>
        public FuncResult<List<tb_PointCheckRecord>> SearchDataFromPointCheckTable(model_SearchCondition_PointCheck conditions, DbSet<tb_PointCheckRecord> dbSet)
        {
            var result = new FuncResult<List<tb_PointCheckRecord>>();
            try
            {
                var query = from wpc in dbSet
                            where (conditions.EquipmentName == null ? true : (wpc.EquipmentName ?? "").Contains(conditions.EquipmentName)) &&
                                (conditions.Operator == null ? true : (wpc.Operator ?? "").Contains(conditions.Operator)) &&
                                (conditions.CheckTime_Begin == null ? true : wpc.CheckTime >= new DateTime(conditions.CheckTime_Begin.Value.Year, conditions.CheckTime_Begin.Value.Month, conditions.CheckTime_Begin.Value.Day, 0, 0, 0)) &&
                                (conditions.CheckTime_End == null ? true : wpc.CheckTime <= new DateTime(conditions.CheckTime_End.Value.Year, conditions.CheckTime_End.Value.Month, conditions.CheckTime_End.Value.Day, 23, 59, 59)) &&
                                (conditions.SeriesNo == null ? true : (wpc.ZC_SeriesNo ?? "").Contains(conditions.SeriesNo)) &&
                                (conditions.Result == null ? true : (wpc.Result ?? "").Contains(conditions.Result.Replace("全部", "")))
                            orderby wpc.dDate descending
                            select wpc;
                var list = query.ToList();
                result.obj_Return = list;
                result.bSuccess = true;
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }

        #region 动态年份查询方法

        /// <summary>
        /// 通用的历史数据查询方法，支持动态年份
        /// </summary>
        /// <param name="year">年份</param>
        /// <param name="conditions">查询条件</param>
        /// <returns></returns>
        public FuncResult<List<object>> SearchDataFromHistoryTableByYear(int year, model_SearchCondition conditions)
        {
            var result = new FuncResult<List<object>>();
            try
            {
                var _context = this._serviceProvider.GetService<AppDbContext>();
                if (_context == null)
                {
                    result.bSuccess = false;
                    result.strMsg = "无法获取到数据库服务";
                    return result;
                }

                // 动态获取对应年份的DbSet属性
                var dbSetPropertyName = $"tb_workpiecedatacapture_history_{year}";
                var dbSetProperty = _context.GetType().GetProperty(dbSetPropertyName);

                if (dbSetProperty == null)
                {
                    result.bSuccess = false;
                    result.strMsg = $"不存在{year}年的历史表：{dbSetPropertyName}";
                    return result;
                }

                var dbSet = dbSetProperty.GetValue(_context);
                if (dbSet == null)
                {
                    result.bSuccess = false;
                    result.strMsg = $"{year}年的历史表DbSet为空";
                    return result;
                }

                var dbSetType = dbSet.GetType();

                // 获取泛型参数类型（实体类型）
                var entityType = dbSetType.GetGenericArguments()[0];

                // 使用反射调用通用查询方法
                var method = this.GetType().GetMethod("SearchDataFromHistoryTableGeneric", BindingFlags.NonPublic | BindingFlags.Instance);
                if (method == null)
                {
                    result.bSuccess = false;
                    result.strMsg = "找不到通用查询方法";
                    return result;
                }

                var genericMethod = method.MakeGenericMethod(entityType);
                var queryResult = genericMethod.Invoke(this, new object[] { dbSet, conditions });

                if (queryResult is FuncResult<List<object>> funcResult)
                {
                    result = funcResult;
                }
                else
                {
                    result.bSuccess = false;
                    result.strMsg = "查询结果类型转换失败";
                }
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }

        /// <summary>
        /// 泛型查询方法，使用反射动态构建查询条件
        /// </summary>
        private FuncResult<List<object>> SearchDataFromHistoryTableGeneric<T>(DbSet<T> dbSet, model_SearchCondition conditions) where T : class
        {
            var result = new FuncResult<List<object>>();
            try
            {
                var query = dbSet.AsQueryable();

                // 动态构建查询条件
                query = ApplySearchConditions(query, conditions);

                // 动态排序 - 按 ZC_Time 降序
                var orderByExpression = BuildPropertyExpression<T, string>("ZC_Time");
                if (orderByExpression != null)
                {
                    query = query.OrderByDescending(orderByExpression);
                }

                var list = query.ToList();
                result.obj_Return = list.Cast<object>().ToList();
                result.bSuccess = true;
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }

        /// <summary>
        /// 应用搜索条件到查询
        /// </summary>
        private IQueryable<T> ApplySearchConditions<T>(IQueryable<T> query, model_SearchCondition conditions) where T : class
        {
            var entityType = typeof(T);

            // 字符串包含查询条件
            var stringConditions = new Dictionary<string, string?>
            {
                { "ZC_SerialNo", conditions.ZC_SerialNo },
                { "ZC_Model", conditions.ZC_Model },
                { "ZC_LaserNo", conditions.ZC_LaserNo },
                { "ZC_Result", conditions.ZC_Result?.Replace("全部", "") },
                { "FLJ_ZT_Model", conditions.FLJ_ZT_Model },
                { "FLJ_ZT_Material", conditions.FLJ_ZT_Material },
                { "FLJ_YCQ_Model", conditions.FLJ_YCQ_Model },
                { "FLJ_YCQ_Material", conditions.FLJ_YCQ_Material },
                { "FLJ_YCQ_Result", conditions.FLJ_YCQ_Result?.Replace("全部", "") },
                { "FLJ_GLH_Model", conditions.FLJ_GLH_Model },
                { "FLJ_GLH_Material", conditions.FLJ_GLH_Material },
                { "FLJ_GLH_Result", conditions.FLJ_GLH_Result?.Replace("全部", "") },
                { "FLJ_ECQ_Model", conditions.FLJ_ECQ_Model },
                { "FLJ_ECQ_Material", conditions.FLJ_ECQ_Material },
                { "FLJ_ECQ_Result", conditions.FLJ_ECQ_Result?.Replace("全部", "") },
                { "FLJ_KZH_Model", conditions.FLJ_KZH_Model },
                { "FLJ_KZH_Material", conditions.FLJ_KZH_Material },
                { "FLJ_KZH_Result", conditions.FLJ_KZH_Result?.Replace("全部", "") },
                { "FLJ_SK_Model", conditions.FLJ_SK_Model },
                { "FLJ_SK_Material", conditions.FLJ_SK_Material },
                { "FLJ_SK_Result", conditions.FLJ_SK_Result?.Replace("全部", "") },
                { "JCY_QM_Result", conditions.JCY_QM_Result?.Replace("全部", "") },
                { "JCY_KTQM_Result", conditions.JCY_KTQM_Result?.Replace("全部", "") },
                { "FLJ_WM_Model", conditions.FLJ_WM_Model },
                { "FLJ_WM_Material", conditions.FLJ_WM_Material },
                { "FLJ_WM_Result", conditions.FLJ_WM_Result?.Replace("全部", "") },
                { "ZC_DM_Result", conditions.ZC_DM_Result?.Replace("全部", "") },
                { "ZC_DM_ScanText", conditions.ZC_DM_ScanText }
            };

            // 应用字符串包含条件
            foreach (var condition in stringConditions)
            {
                if (!string.IsNullOrEmpty(condition.Value))
                {
                    var containsExpression = BuildStringContainsExpression<T>(condition.Key, condition.Value);
                    if (containsExpression != null)
                    {
                        query = query.Where(containsExpression);
                    }
                }
            }

            // 数值范围查询条件
            if (conditions.FLJ_KZH_Begin.HasValue)
            {
                var expression = BuildNumericComparisonExpression<T, double?>("FLJ_KZH_Value", conditions.FLJ_KZH_Begin.Value, ">=");
                if (expression != null) query = query.Where(expression);
            }
            if (conditions.FLJ_KZH_End.HasValue)
            {
                var expression = BuildNumericComparisonExpression<T, double?>("FLJ_KZH_Value", conditions.FLJ_KZH_End.Value, "<=");
                if (expression != null) query = query.Where(expression);
            }

            // 整数相等查询条件
            if (conditions.JCY_QM_Program.HasValue)
            {
                var expression = BuildNumericComparisonExpression<T, int?>("JCY_QM_Program", conditions.JCY_QM_Program.Value, "==");
                if (expression != null) query = query.Where(expression);
            }
            if (conditions.JCY_KTQM_Program.HasValue)
            {
                var expression = BuildNumericComparisonExpression<T, int?>("JCY_KTQM_Program", conditions.JCY_KTQM_Program.Value, "==");
                if (expression != null) query = query.Where(expression);
            }

            // 压力值范围查询
            if (conditions.JCY_QM_Pressure_Begin.HasValue)
            {
                var expression = BuildNumericComparisonExpression<T, double?>("JCY_QM_Pressure", conditions.JCY_QM_Pressure_Begin.Value, ">=");
                if (expression != null) query = query.Where(expression);
            }
            if (conditions.JCY_QM_Pressure_End.HasValue)
            {
                var expression = BuildNumericComparisonExpression<T, double?>("JCY_QM_Pressure", conditions.JCY_QM_Pressure_End.Value, "<=");
                if (expression != null) query = query.Where(expression);
            }

            // 泄漏值范围查询
            if (conditions.JCY_QM_Leak_Begin.HasValue)
            {
                var expression = BuildNumericComparisonExpression<T, double?>("JCY_QM_Leak", conditions.JCY_QM_Leak_Begin.Value, ">=");
                if (expression != null) query = query.Where(expression);
            }
            if (conditions.JCY_QM_Leak_End.HasValue)
            {
                var expression = BuildNumericComparisonExpression<T, double?>("JCY_QM_Leak", conditions.JCY_QM_Leak_End.Value, "<=");
                if (expression != null) query = query.Where(expression);
            }

            // 壳体气密压力值范围查询
            if (conditions.JCY_KTQM_Pressure_Begin.HasValue)
            {
                var expression = BuildNumericComparisonExpression<T, double?>("JCY_KTQM_Pressure", conditions.JCY_KTQM_Pressure_Begin.Value, ">=");
                if (expression != null) query = query.Where(expression);
            }
            if (conditions.JCY_KTQM_Pressure_End.HasValue)
            {
                var expression = BuildNumericComparisonExpression<T, double?>("JCY_KTQM_Pressure", conditions.JCY_KTQM_Pressure_End.Value, "<=");
                if (expression != null) query = query.Where(expression);
            }

            // 壳体气密泄漏值范围查询
            if (conditions.JCY_KTQM_Leak_Begin.HasValue)
            {
                var expression = BuildNumericComparisonExpression<T, double?>("JCY_KTQM_Leak", conditions.JCY_KTQM_Leak_Begin.Value, ">=");
                if (expression != null) query = query.Where(expression);
            }
            if (conditions.JCY_KTQM_Leak_End.HasValue)
            {
                var expression = BuildNumericComparisonExpression<T, double?>("JCY_KTQM_Leak", conditions.JCY_KTQM_Leak_End.Value, "<=");
                if (expression != null) query = query.Where(expression);
            }

            // 日期范围查询
            if (conditions.dDate_Begin.HasValue)
            {
                var beginDate = new DateTime(conditions.dDate_Begin.Value.Year, conditions.dDate_Begin.Value.Month, conditions.dDate_Begin.Value.Day, 0, 0, 0);
                var expression = BuildDateComparisonExpression<T>("dDate", beginDate, ">=");
                if (expression != null) query = query.Where(expression);
            }
            if (conditions.dDate_End.HasValue)
            {
                var endDate = new DateTime(conditions.dDate_End.Value.Year, conditions.dDate_End.Value.Month, conditions.dDate_End.Value.Day, 23, 59, 59);
                var expression = BuildDateComparisonExpression<T>("dDate", endDate, "<=");
                if (expression != null) query = query.Where(expression);
            }

            return query;
        }

        /// <summary>
        /// 构建字符串包含表达式
        /// </summary>
        private Expression<Func<T, bool>>? BuildStringContainsExpression<T>(string propertyName, string value)
        {
            try
            {
                var entityType = typeof(T);
                var property = entityType.GetProperty(propertyName);
                if (property == null || property.PropertyType != typeof(string)) return null;

                var parameter = Expression.Parameter(entityType, "x");
                var propertyAccess = Expression.Property(parameter, property);

                // 检查属性是否为null
                var nullCheck = Expression.NotEqual(propertyAccess, Expression.Constant(null, typeof(string)));

                // 调用Contains方法
                var containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
                var containsCall = Expression.Call(propertyAccess, containsMethod!, Expression.Constant(value));

                // 组合null检查和Contains调用
                var combined = Expression.AndAlso(nullCheck, containsCall);

                return Expression.Lambda<Func<T, bool>>(combined, parameter);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 构建数值比较表达式
        /// </summary>
        private Expression<Func<T, bool>>? BuildNumericComparisonExpression<T, TProperty>(string propertyName, object value, string operation)
        {
            try
            {
                var entityType = typeof(T);
                var property = entityType.GetProperty(propertyName);
                if (property == null || property.PropertyType != typeof(TProperty)) return null;

                var parameter = Expression.Parameter(entityType, "x");
                var propertyAccess = Expression.Property(parameter, property);
                var constantValue = Expression.Constant(value, typeof(TProperty));

                Expression comparison = operation switch
                {
                    ">=" => Expression.GreaterThanOrEqual(propertyAccess, constantValue),
                    "<=" => Expression.LessThanOrEqual(propertyAccess, constantValue),
                    "==" => Expression.Equal(propertyAccess, constantValue),
                    ">" => Expression.GreaterThan(propertyAccess, constantValue),
                    "<" => Expression.LessThan(propertyAccess, constantValue),
                    _ => throw new ArgumentException($"不支持的操作符: {operation}")
                };

                return Expression.Lambda<Func<T, bool>>(comparison, parameter);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 构建日期比较表达式
        /// </summary>
        private Expression<Func<T, bool>>? BuildDateComparisonExpression<T>(string propertyName, DateTime value, string operation)
        {
            try
            {
                var entityType = typeof(T);
                var property = entityType.GetProperty(propertyName);
                if (property == null || property.PropertyType != typeof(DateTime?)) return null;

                var parameter = Expression.Parameter(entityType, "x");
                var propertyAccess = Expression.Property(parameter, property);
                var constantValue = Expression.Constant(value, typeof(DateTime?));

                Expression comparison = operation switch
                {
                    ">=" => Expression.GreaterThanOrEqual(propertyAccess, constantValue),
                    "<=" => Expression.LessThanOrEqual(propertyAccess, constantValue),
                    "==" => Expression.Equal(propertyAccess, constantValue),
                    ">" => Expression.GreaterThan(propertyAccess, constantValue),
                    "<" => Expression.LessThan(propertyAccess, constantValue),
                    _ => throw new ArgumentException($"不支持的操作符: {operation}")
                };

                return Expression.Lambda<Func<T, bool>>(comparison, parameter);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 构建属性访问表达式
        /// </summary>
        private Expression<Func<T, TProperty>>? BuildPropertyExpression<T, TProperty>(string propertyName)
        {
            try
            {
                var entityType = typeof(T);
                var property = entityType.GetProperty(propertyName);
                if (property == null) return null;

                var parameter = Expression.Parameter(entityType, "x");
                var propertyAccess = Expression.Property(parameter, property);

                // 如果属性类型不匹配，尝试转换
                if (property.PropertyType != typeof(TProperty))
                {
                    var convertExpression = Expression.Convert(propertyAccess, typeof(TProperty));
                    return Expression.Lambda<Func<T, TProperty>>(convertExpression, parameter);
                }

                return Expression.Lambda<Func<T, TProperty>>(propertyAccess, parameter);
            }
            catch
            {
                return null;
            }
        }

        #endregion
    }
}
